package com.scale.service.conversation.service.impl;

import com.example.conversation.dto.SendMessageDTO;
import com.example.conversation.entity.Conversations;
import com.example.conversation.entity.Messages;
import com.example.conversation.vo.MessageVO;
import com.scale.service.conversation.mapper.MessagesMapper;
import com.scale.service.conversation.service.ConversationsService;
import com.scale.service.conversation.service.MessagesService;
import com.scale.service.character.service.AiCharactersService;
import com.example.character.entity.AiCharacters;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 对话消息表 服务实现类
 * </p>
 *
 * @author crp
 * @since 2025-09-24
 */
@Service
public class MessagesServiceImpl extends ServiceImpl<MessagesMapper, Messages> implements MessagesService {

    @Autowired
    private ConversationsService conversationsService;

    @Autowired
    private AiCharactersService aiCharactersService;

    @Value("${ai.model.provider:qwen}")
    private String aiProvider;

    @Value("${ai.model.name:qwen-turbo}")
    private String defaultModelName;

    @Value("${ai.context.max-messages:10}")
    private Integer maxContextMessages;

    @Value("${dashscope.api-key:}")
    private String dashscopeApiKey;

    @Override
    public List<MessageVO> getChatHistory(Long characterId, Long userId, Integer page, Integer size) {
        // 获取对话
        QueryWrapper<Conversations> conversationQuery = new QueryWrapper<>();
        conversationQuery.eq("user_id", userId)
                        .eq("character_id", characterId)
                        .orderByDesc("created_at")
                        .last("LIMIT 1");

        Conversations conversation = conversationsService.getOne(conversationQuery);
        if (conversation == null) {
            return List.of();
        }

        // 分页查询消息
        Page<Messages> messagePage = new Page<>(page, size);
        QueryWrapper<Messages> messageQuery = new QueryWrapper<>();
        messageQuery.eq("conversation_id", conversation.getId())
                   .orderByAsc("created_at");

        IPage<Messages> messagesPage = page(messagePage, messageQuery);

        // 转换为VO
        return messagesPage.getRecords().stream().map(message -> {
            MessageVO vo = new MessageVO();
            BeanUtils.copyProperties(message, vo);
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public MessageVO sendMessageAndGetReply(SendMessageDTO sendMessageDTO, Long userId) {
        // 创建或获取对话
        Conversations conversation;
        if (sendMessageDTO.getConversationId() != null && sendMessageDTO.getConversationId() > 0) {
            // 尝试获取现有对话
            conversation = conversationsService.getById(sendMessageDTO.getConversationId());
            // 如果对话不存在，创建新对话
            if (conversation == null) {
                conversation = conversationsService.createOrGetConversation(userId, sendMessageDTO.getCharacterId());
            }
        } else {
            // conversationId为null或0时，创建新对话
            conversation = conversationsService.createOrGetConversation(userId, sendMessageDTO.getCharacterId());
        }

        // 确保对话存在
        if (conversation == null) {
            throw new RuntimeException("无法创建或获取对话记录，请检查角色ID是否正确");
        }

        // 保存用户消息
        Messages userMessage = new Messages();
        userMessage.setConversationId(conversation.getId());
        userMessage.setSenderType(1); // 1-用户
        userMessage.setContent(sendMessageDTO.getContent());
        userMessage.setContentType(sendMessageDTO.getContentType());
        userMessage.setVoiceUrl(sendMessageDTO.getVoiceUrl());
        userMessage.setCreatedAt(LocalDateTime.now());
        save(userMessage);

        // 获取AI角色信息
        AiCharacters character = aiCharactersService.getById(sendMessageDTO.getCharacterId());

        // 构建对话上下文（包含历史记忆）
        String conversationContext = buildConversationContext(
                sendMessageDTO.getCharacterId(), userId, sendMessageDTO.getContent());

        // 调用AI模型获取回复（带记忆功能）
        String aiReply = getAIReply(character, sendMessageDTO.getContent(),
                conversationContext, userId);

        // 保存AI回复
        Messages aiMessage = new Messages();
        aiMessage.setConversationId(conversation.getId());
        aiMessage.setSenderType(2); // 2-AI角色
        aiMessage.setContent(aiReply);
        aiMessage.setContentType("text");
        aiMessage.setAiResponseTime(1500); // 模拟响应时间
        aiMessage.setCreatedAt(LocalDateTime.now());
        save(aiMessage);

        // 更新对话统计
        conversation.setTotalMessages(conversation.getTotalMessages() + 2);
        conversation.setUpdatedAt(LocalDateTime.now());
        conversationsService.updateById(conversation);

        // 返回AI消息
        MessageVO vo = new MessageVO();
        BeanUtils.copyProperties(aiMessage, vo);
        return vo;
    }

    @Override
    public boolean updateMessageStatus(Long messageId, String status) {
        Messages message = getById(messageId);
        if (message == null) {
            return false;
        }

        // 这里可以扩展Messages实体类添加status字段，或者使用其他方式存储状态
        // 这里暂时返回true表示成功
        return true;
    }

    /**
     * 根据角色配置获取AI回复
     */
    private String getAIReply(AiCharacters character, String userMessage, String conversationHistory, Long userId) {
        try {
            // 根据配置的AI服务提供商调用不同的模型
            switch (aiProvider.toLowerCase()) {
                case "qwen":
                case "tongyi":
                    return callTongyiModel(character, userMessage, conversationHistory, userId);
                case "openai":
                case "chatgpt":
                    return callOpenAIModel(character, userMessage, conversationHistory, userId);
                case "claude":
                    return callClaudeModel(character, userMessage, conversationHistory, userId);
                default:
                    return generateDefaultReply(character, userMessage);
            }
        } catch (Exception e) {
            System.err.println("AI模型调用失败: " + e.getMessage());
            return generateDefaultReply(character, userMessage);
        }
    }

    /**
     * 构建对话上下文（包含记忆）
     */
    private String buildConversationContext(Long characterId, Long userId, String currentMessage) {
        // 获取角色信息
        AiCharacters character = aiCharactersService.getById(characterId);
        if (character == null) {
            return currentMessage;
        }

        // 获取最近的对话历史
        List<Messages> recentMessages = getRecentMessages(characterId, userId, maxContextMessages);

        // 构建完整的对话上下文
        StringBuilder context = new StringBuilder();

        // 添加角色系统提示
        if (character.getSystemPrompt() != null && !character.getSystemPrompt().isEmpty()) {
            context.append("系统提示: ").append(character.getSystemPrompt()).append("\n\n");
        }

        // 添加角色人设
        context.append("角色设定:\n");
        context.append("- 名称: ").append(character.getName()).append("\n");
        context.append("- 性格: ").append(character.getPersonality()).append("\n");
        context.append("- 背景: ").append(character.getBackground()).append("\n\n");

        // 添加对话历史
        if (!recentMessages.isEmpty()) {
            context.append("对话历史:\n");
            for (Messages message : recentMessages) {
                String sender = message.getSenderType() == 1 ? "用户" : character.getName();
                context.append(sender).append(": ").append(message.getContent()).append("\n");
            }
            context.append("\n");
        }

        // 添加当前消息
        context.append("用户: ").append(currentMessage).append("\n");
        context.append(character.getName()).append(": ");

        return context.toString();
    }

    /**
     * 调用通义千问模型
     */
    private String callTongyiModel(AiCharacters character, String userMessage, String conversationHistory, Long userId) {
        try {
            Generation gen = new Generation();

            // 构建消息列表
            List<Message> messages = new ArrayList<>();

            // 添加系统消息（角色人设）
            String systemPrompt = buildSystemPrompt(character);
            messages.add(Message.builder()
                    .role(Role.SYSTEM.getValue())
                    .content(systemPrompt)
                    .build());

            // 添加对话历史
            if (conversationHistory != null && !conversationHistory.isEmpty()) {
                parseAndAddConversationHistory(messages, conversationHistory, character.getName());
            }

            // 添加当前用户消息
            messages.add(Message.builder()
                    .role(Role.USER.getValue())
                    .content(userMessage)
                    .build());



            // 使用配置文件中的API密钥，如果为空则尝试环境变量
            String apiKey = (dashscopeApiKey != null && !dashscopeApiKey.trim().isEmpty())
                    ? dashscopeApiKey.trim()
                    : System.getenv("DASHSCOPE_API_KEY");

            if (apiKey == null || apiKey.trim().isEmpty()) {
                throw new RuntimeException("API密钥未配置，请检查application.yml中的dashscope.api-key或环境变量DASHSCOPE_API_KEY");
            }
            System.err.println(System.getenv("DASHSCOPE_API_KEY"));
            System.out.println("使用API密钥: " + apiKey.substring(0, 10) + "...");

            GenerationParam param = GenerationParam.builder()
                    .apiKey(apiKey)
                    .model(defaultModelName)
                    .messages(messages)
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .topP(0.8) // 控制生成的随机性
                    .temperature(0.7f) // 控制创造性
                    .maxTokens(1000) // 限制回复长度
                    .build();

            GenerationResult result = gen.call(param);

            if (result != null && result.getOutput() != null && result.getOutput().getChoices() != null) {
                String aiReply = result.getOutput().getChoices().get(0).getMessage().getContent();
                return postProcessAIReply(aiReply, character);
            }

            return generateContextualReply(character, userMessage, conversationHistory);

        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.err.println("通义千问调用失败: " + e.getMessage());
            return generateContextualReply(character, userMessage, conversationHistory);
        }
    }

    /**
     * 构建系统提示词
     */
    private String buildSystemPrompt(AiCharacters character) {
        StringBuilder systemPrompt = new StringBuilder();

        // 基础角色设定
        systemPrompt.append(String.format("你是%s，", character.getName()));

        if (character.getPersonality() != null && !character.getPersonality().isEmpty()) {
            systemPrompt.append(String.format("性格特点：%s。", character.getPersonality()));
        }

        if (character.getBackground() != null && !character.getBackground().isEmpty()) {
            systemPrompt.append(String.format("背景：%s。", character.getBackground()));
        }

        // 添加自定义系统提示
        if (character.getSystemPrompt() != null && !character.getSystemPrompt().isEmpty()) {
            systemPrompt.append(character.getSystemPrompt());
        }

        // 添加通用行为指导
        systemPrompt.append("\n请保持角色一致性，用温暖、耐心的语气与用户交流。");
        systemPrompt.append("回复要简洁明了，避免过长的回答。");
        systemPrompt.append("如果用户情绪低落，要给予关怀和支持。");

        return systemPrompt.toString();
    }

    /**
     * 解析对话历史并添加到消息列表
     */
    private void parseAndAddConversationHistory(List<Message> messages, String conversationHistory, String characterName) {
        if (conversationHistory == null || conversationHistory.isEmpty()) {
            return;
        }

        // 简单的对话历史解析（假设格式为：用户: xxx\n角色名: xxx\n）
        String[] lines = conversationHistory.split("\n");
        for (String line : lines) {
            if (line.trim().isEmpty()) continue;

            if (line.startsWith("用户: ")) {
                String content = line.substring(3).trim();
                if (!content.isEmpty()) {
                    messages.add(Message.builder()
                            .role(Role.USER.getValue())
                            .content(content)
                            .build());
                }
            } else if (line.startsWith(characterName + ": ")) {
                String content = line.substring(characterName.length() + 2).trim();
                if (!content.isEmpty()) {
                    messages.add(Message.builder()
                            .role(Role.ASSISTANT.getValue())
                            .content(content)
                            .build());
                }
            }
        }
    }

    /**
     * 后处理AI回复
     */
    private String postProcessAIReply(String aiReply, AiCharacters character) {
        if (aiReply == null || aiReply.isEmpty()) {
            return generateDefaultReply(character, "");
        }

        // 移除可能的前缀（如角色名）
        String characterName = character.getName();
        if (aiReply.startsWith(characterName + ":") || aiReply.startsWith(characterName + "：")) {
            aiReply = aiReply.substring(characterName.length() + 1).trim();
        }

        // 限制回复长度
        if (aiReply.length() > 500) {
            aiReply = aiReply.substring(0, 497) + "...";
        }

        return aiReply;
    }

    /**
     * 调用OpenAI模型
     */
    private String callOpenAIModel(AiCharacters character, String userMessage, String conversationHistory, Long userId) {
        // TODO: 集成OpenAI API
        return generateContextualReply(character, userMessage, conversationHistory);
    }

    /**
     * 调用Claude模型
     */
    private String callClaudeModel(AiCharacters character, String userMessage, String conversationHistory, Long userId) {
        // TODO: 集成Anthropic Claude API
        return generateContextualReply(character, userMessage, conversationHistory);
    }

    /**
     * 生成默认回复（降级方案）
     */
    private String generateDefaultReply(AiCharacters character, String userMessage) {
        String characterName = character.getName();
        String personality = character.getPersonality();

        return String.format("作为%s，我理解你的想法。%s 让我们来讨论一下这个问题。",
               characterName, personality != null ? personality : "");
    }

    /**
     * 生成有上下文的回复
     */
    private String generateContextualReply(AiCharacters character, String userMessage, String conversationHistory) {
        String characterName = character.getName();
        String personality = character.getPersonality();

        // 根据对话历史生成更智能的回复
        if (conversationHistory != null && conversationHistory.contains("你好")) {
            return String.format("很高兴继续和你聊天！作为%s，%s", characterName,
                   personality != null ? personality + "我想了解你今天怎么样？" : "我在这里倾听你。");
        }

        return String.format("作为%s，我理解你的想法。%s 让我们深入聊聊这个话题。",
               characterName, personality != null ? personality : "");
    }

    /**
     * 获取最近的对话消息
     */
    private List<Messages> getRecentMessages(Long characterId, Long userId, Integer limit) {
        // 获取最近的对话
        QueryWrapper<Conversations> conversationQuery = new QueryWrapper<>();
        conversationQuery.eq("user_id", userId)
                        .eq("character_id", characterId)
                        .orderByDesc("updated_at")
                        .last("LIMIT 1");

        Conversations conversation = conversationsService.getOne(conversationQuery);
        if (conversation == null) {
            return List.of();
        }

        // 获取最近的消息
        QueryWrapper<Messages> messageQuery = new QueryWrapper<>();
        messageQuery.eq("conversation_id", conversation.getId())
                   .orderByDesc("created_at")
                   .last("LIMIT " + limit);

        List<Messages> messages = list(messageQuery);

        // 按时间正序返回（最早的在前面）
        return messages.stream()
                .sorted((m1, m2) -> m1.getCreatedAt().compareTo(m2.getCreatedAt()))
                .collect(Collectors.toList());
    }
}
